<template>
  <div>
    <el-dialog width="60%" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag
               :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-jinduguanli1"></i>
           <span>{{ title }}</span>
      </span>

      <div class="WholeScroll" style="max-height: 650px; overflow: auto;padding: 0 15px;">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules"
                 class="measurepaycompensation_detail_form">
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="隐患类别"
                prop="name"
                :label-width="formlabelWidth"
              >
                <el-input
                  v-model="formBaseData.name"
                  placeholder
                  disabled
                >
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item
                label="隐患级别"
                prop="hiddenDangerLevel"
                :label-width="formlabelWidth"
              >
                <el-select
                  style="width: 100%"
                  v-model="formBaseData.hiddenDangerLevel"
                  placeholder="选择隐患级别"
                  :disabled="detailType == 'check'"
                >
                  <el-option
                    v-for="item in hiddenDangerLevelArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="事故隐患"
                :label-width="formlabelWidth"
              >
                <el-select
                  style="width: 100%"
                  v-model="formBaseData.accidentPotential"
                  placeholder="选择事故隐患"
                  clearable
                  :disabled="detailType == 'check'"
                >
                  <el-option
                    v-for="item in accidentPotentialArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item
                label="整改时限"
                :label-width="formlabelWidth"
                prop="rectificationTimeLimit"
              >
                <el-input
                  class="contract-ele"
                  type="number"
                  v-model="formBaseData.rectificationTimeLimit"
                  placeholder
                  :disabled="detailType === 'check'"
                >
                  <template slot="append">天</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="排查内容"
                prop="checkContent"
                :label-width="formlabelWidth"
              >
                <el-input
                  style="width: 100%"
                  class="contract-ele-long"
                  v-model="formBaseData.checkContent"
                  placeholder="请输入排查内容"
                  rows="8"
                  type="textarea"
                  :disabled="detailType === 'check'">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="整改要求"
                :label-width="formlabelWidth"
              >
                <el-input
                  style="width: 100%"
                  class="contract-ele-long"
                  v-model="formBaseData.rectificationRequirements"
                  placeholder="请输入整改要求"
                  rows="8"
                  type="textarea"
                  :disabled="detailType === 'check'">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>


      <div slot="footer" class="dialog-footer">
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading2"
                     @click="handleClickDeal('submit', {flag: 1})"><i
            class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'

import WfProcess from "@/components/WorkFlow/process";
import BpmnForm from "@/components/ExtBpmn/ExtForm/bpmn-form";
import PopBtn from "@/components/ExtBpmn/Btn";
import startMixin from "@/mixins/wfStartMixin";
import approveMixin from "@/mixins/wfApproveMixin";
import hiddenDangerItems from '@/api/buss/hiddendangeritems'
export default {
  name: 'hiddendangeritems-detail',
  components: {
    WfProcess,
    BpmnForm,
    PopBtn
  },
  mixins: [startMixin, approveMixin],

  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  data() {
    return {

      // 流程参数 str ####################################
      isShowBpmn : false,
      isMultiple:false,
      variables:{},
      entity: {},
      fileList: [],
      wfNode: {},
      showBpmnForm:false,
      setManage:'',//项目公司选项:1项目办，2指挥部
      readonly:false,
      // 流程参数 end ####################################
      hiddenDangerLevelArr:[
        {"id":"一级","name":"一级"},
        {"id":"二级","name":"二级"},
        {"id":"三级","name":"三级"},
        {"id":"四级","name":"四级"},
      ],
      accidentPotentialArr:[
        {"id":"1","name":"一般"},
        {"id":"2","name":"重大"},
      ],

      rowIndex: -1, //行索引
      columnIndex: -1, //列索引
      actionType: '查看',
      title: '新增隐患',

      sectionTree: [], // 标段下拉
      referenceOtherDataList: [],
      canEdit: true,


      //存放图片的数组
      fileListArray: [],
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      activeName: 'first', //
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'hiddenDangerItems',
          part: 'one',
          compoName: 'fileOne'
        }
      },
      tabShow: false,
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      radioValue: '',//单选按钮选中的值
      formlabelWidth: '155px', // 表单左侧标题宽度
      // 表单基本信息内容
      addSectionId:'',
      // canEditPlan:true, // 开始做计划时 不允许修改form 表单
      formBaseData: {
        projectId: '',
        code: '',
        id: '',
        name: '',
        parentCode: '',
        createrName: '',
        hiddenDangerLevel: '',
        rectificationTimeLimit: '',
        hiddenDangerCategoryId: '',
        accidentPotential: '',
        checkContent: '',
        rectificationRequirements: '',
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      // 表单基本信息验证
      formBaseRules: {
        accidentPotential: [
          {
            required: true,
            message: '事故隐患',
            trigger: 'change'
          }
        ],
        hiddenDangerLevel: [
          {
            required: true,
            message: '请选择隐患级别',
            trigger: 'change'
          }
        ],
        troubleType: [
          {
            required: true,
            message: '请填写隐患类别',
            trigger: 'blur'
          }
        ],
        rectificationTimeLimit: [
          {
            required: true,
            message: '请填写整改时限',
            trigger: 'blur'
          }
        ],
        checkContent: [
          {
            required: true,
            message: '请填写排查内容',
            trigger: 'blur'
          }
        ],
      },
      treeVOS: [],
      tableColumn: [],
      tabsYear: null,
      //  现在编辑的单元格标记

      showAudit: false,
      isLoading2: false,

      //  显示导入错误日志
      showErrorLog: false,
      errorLog: [],
      activeName3: "",
    }
  },
  watch: {
    postDetail(value) {
      this.formShow = value.show
      // 显示详情弹窗
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.actionType = value.typeName
      this.showAudit = true
      this.formBaseData.name = value.name
      this.formBaseData.parentCode = value.chooseTreeData.code
      this.formBaseData.projectId = value.chooseTreeData.projectId
      this.formBaseData.hiddenDangerCategoryId = value.chooseTreeData.id
      console.log(this.formBaseData)

      // 详情id
      this.detailId = value.detailId?value.detailId:'';
      if (this.detailType == 'build') {
        this.addSectionId = value.addSectionId
        this.initData();
      }


      // 公司下拉要查
      //this.fetchWorkSectionList()
      // 非新建详情时 获取详情
      if (this.detailType == 'build') {
        this.tabShow = false;
      } else {
        // this.getAllSecTree();
        // 获取详情请求
        this.getDetail();
      }
    }
  },
  methods: {
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },
    /**
     * 加载文件
     **/
    loadFiles() {
      this.$nextTick(()=>{
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })

    },
    fetchData() {
      this.$emit('reload')
    },

    cancel() {
      this.handleClickDeal('cancel')
    },

    onSave(_, callback) {
      this.handleClickDeal('submit', { flag: 1 }, callback)
    },

    onComplete(data) {
      this.wfNode = data
    },



    /** 流程方法end  **/

    tableRowClassName({ row, rowIndex }) {
      // 把每一行的索引放到row里
      row.index = rowIndex;
    },
    tableCellClassName({ column, columnIndex }) {
      // 把每一列的索引放到column里
      column.index = columnIndex;
    },
    cellClick(row, column) {
      if(row.isLeaf == '1'){
        this.rowIndex = row.index;
        this.columnIndex = column.index;
      }
    },
    // 失去焦点
    inputBlur(type,row) {
      if(type == 'count'){
        if(row.unitprice){
          row.comprehensiveOutputWyPlan = ((row.unitprice * row.numberPlan)/10000).toFixed(6)
        }
      }
      this.rowIndex = -1;
      this.columnIndex = -1;

      this.calculateParentValue()
    },
    calculateParentValue(){
      let calculateParentValue = function(node){
        let sum = 0
        node.children.forEach((i,t)=>{
          if(i.isLeaf == '1'){
            sum = sum + Number(i.comprehensiveOutputWyPlan)
          }else {
            if(i.hasOwnProperty('children')&&i.children.length>0){
              sum = sum + calculateParentValue(i)
            }
          }
        })
        node.comprehensiveOutputWyPlan = sum.toFixed(6)
        node.isCalculate = true
        return sum
      }
      let treeData = JSON.parse(JSON.stringify(this.formBaseData.treeVOS))
      treeData.forEach((item,index)=>{
        calculateParentValue(item);
      })
      this.$set(this.formBaseData,'treeVOS',treeData)
    },
    initData(){
      // if (this.detailType == 'build') {
      //   projectSectionInfo.getAllSecTree().then(res => {
      //     if (res.code === 200) {
      //       var data = res.data;
      //       this.sectionTree = data
      //       if(this.detailType == 'build'){
      //         this.formBaseData.sectionId = this.addSectionId;
      //       }
      //     } else {
      //       msgUtil.error2(res.data.message)
      //     }
      //   })
      // }
    },


    getAllSecTree(){
      projectSectionInfo.getAllSecTree().then(res => {
        if (res.code === 200) {
          var data = res.data;
          this.sectionTree = data
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },

    // 获取版本号
    getIntVersion(){
      let postData = {
        sectionId:this.formBaseData.sectionId
      }
      this.$httpPost(`buss/progressscheduletotal/getIntVersion`,postData).then(res => {
        if (res.code === 200) {
          this.formBaseData.versionNumber = res.data;
        }else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })
    },

    // 获取上个日期
    getBeforeVersionDate(){
      let postData = {
        sectionId:this.formBaseData.sectionId
      }
      this.$httpPost(`buss/progressscheduletotal/getBeforeVersionDate`,this.formBaseData).then(res => {
        if (res.code === 200) {
          this.formBaseData.referenceOtherData = res.data
        }else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })
    },


    planStartDateChange() {
      if (this.formBaseData.dateEnd !== '' && this.formBaseData.dateStart > this.formBaseData.dateEnd) {
        this.formBaseData.dateStart = ''
        this.$messageWarning("计划开始时间不能大于计划结束时间，请重新填写！");
      }
    },
    planEndeDateChange() {
      if (this.formBaseData.dateStart !== '' && this.formBaseData.dateStart > this.formBaseData.dateEnd) {
        this.formBaseData.dateEnd = ''
        this.$messageWarning("计划结束时间不能小于计划开始时间，请重新填写！");
      }
    },
    discountHeaderStyle({row, column, rowIndex, columnIndex}) {
      if (rowIndex == 1) {
        return {display: 'none'}
      }
    },
    submit(flag, callback) {
      if(this.detailType == 'build'){
        console.log(this.formBaseData)
        hiddenDangerItems.submit(this.formBaseData).then(res => {
          if (res.code == 200) {
            this.detailId = res.data.id
            this.$messageSuccess("保存成功")
          } else {
            this.$messageError(res.data.message);
          }
          if (callback) callback();
        }).catch(e => {
          console.log(e);
          this.$messageError("请求保存数据失败")
          if (callback) callback();
        }).finally(res => {
          if (callback) callback();
        })
      } else {
        hiddenDangerItems.resubmit(this.formBaseData).then(res => {
          if (res.code == 200) {
            this.$messageSuccess("保存成功")
          } else {
            this.$messageError(res.data.message);
          }
          if (callback) callback();
        }).catch(e => {
          console.log(e);
          this.$messageError("请求保存数据失败")
          if (callback) callback();
        }).finally(res => {
          if (callback) callback();
        })
      }
    },


    prepareData() {
      if(!this.formBaseData.sectionId){
        this.$messageWarning("标段不能为空");
        return
      }
      if(!this.formBaseData.dateStart){
        this.$messageWarning("开始时间不能为空");
        return
      }
      if(!this.formBaseData.dateEnd){
        this.$messageWarning("结束时间不能为空");
        return
      }
      this.tabShow = true;
      if(this.formBaseData.referenceOtherData){
        // 当上一版本在的时候 通过历史数据初始化
        this.prepareDataHis();
      }else{
        // 初始化第一版数据
        this.prepareDataCs();
      }
    },


    // 初始第一版数据
    prepareDataCs(){
      let postData = {
        sectionId: this.formBaseData.sectionId,
        dateStart: this.formBaseData.dateStart,
        dateEnd: this.formBaseData.dateEnd,
      }
      this.$httpPost(`buss/progressscheduletotal/prepareData`,postData).then(res => {
        if (res.code === 200) {
          this.formBaseData.treeVOS = res.data
        }else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })
    },

    // 最新的一期数据 进行初始化数据
    prepareDataHis(){
      let postData = {
        sectionId: this.formBaseData.sectionId,
        dateStart: this.formBaseData.dateStart,
        dateEnd: this.formBaseData.dateEnd,
      }
      this.$httpPost(`buss/progressscheduletotal/prepareDataByBeforeData`,postData).then(res => {
        if (res.code === 200) {
          this.formBaseData.treeVOS = res.data
        }else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })
    },

    // 获取详情请求 api
    getDetail() {
      this.isLoading2 = true
      hiddenDangerItems.getOne(this.detailId).then(res => {
        this.isLoading2 = false

        if (res.code == 200) {

          this.formBaseData = Object.assign({}, this.formBaseData, res.data)
          console.log(this.formBaseData)
          this.$forceUpdate()
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        this.isLoading2 = false
        console.log('请求出现错误', res);
        this.$messageError(this.$route.name + '请求失败')
      })
    },

    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res,callback) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':

          this.showAudit = false
          this.isShowBpmn = false
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            sectionId: '',
            percentage: '',
            remarks: '',
            date: '',
            protocolNum: '',
            createrName: '',
          }, // 表单基本信息内容
            this.radioValue = ''
          this.sectionTree= []
          this.formShow = false
          //清空按钮 数组
          this.fileListArray = []
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 提交详情
              this.submit((flag), () => {
                this.formShow = false
                // 传值给父组件刷新列表
                this.$emit('reloadList')
              })
            } else {
              callback && callback();
            }
          })
          break
        // 删除
        case 'delete':
          this.$prompt('删除理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({value}) => {
            if (value === null || value === '') {
              this.$messageError('请填写删除理由后重试')
              return
            }
            this.sealDealHttp(res.url, ``, {}, {
              id: this.detailId,
              description: value,
            }, () => {
              this.$messageSuccess('删除成功!')
              onEmit.$emit('Ajax')
              this.formShow = false
              //清空按钮 数组
              this.fileListArray = []
              // 传值给父组件刷新列表
              this.$emit('reloadList')
            })
          }).catch(() => {
            console.log('请求出现错误',);
          });
          break

      }
    },
    numFilter(value) {
      try {
        if (value) {
          value = Number.parseFloat(value.toString())
        } else {
          return value;
        }
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        console.log(e);
        return value
      }
    },
  },

  filters: {
    numFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ""
      }
    },
    numFilter2(value) {
      try {
        let before = value.toFixed(2)
        return before
      } catch (e) {
        return ""
      }
    }
  },
  created() {
  },
}
</script>

<style scoped lang="scss">
  .fee_add {
    color: #008fe0;
    border-color: #008fe0;
    float: right;
    margin-bottom: 10px;
  }

  .el-input__inner {
    width: 291px;
  }

  .dialogTableDiv {
    width: 100%;
    margin: 0 auto;

    .tableTitle {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;

      p {
        font-size: 16px;
      }

      .add {
        background-color: #ffffff;
        color: rgb(73, 163, 250);
      }
    }
  }

  .meterage-manage-detail .el-date-editor.el-input.el-input--prefix.el-input--suffix.el-date-editor--date {
    width: 255px;
  }

  /*.tree-menu {*/
  /*color: black !important;*/
  /*div{*/
  /*color: black !important;*/
  /*}*/
  /*}*/
</style>
<style lang="scss">
  .el-message-box {
    .el-message-box__btns {
      .el-button {
        font-size: 14px;
      }
    }
  }
</style>
